package com.ncu702.backend.controller;


import cn.hutool.core.lang.UUID;
import com.ncu702.backend.common.BaseResponse;
import com.ncu702.backend.common.ErrorCode;
import com.ncu702.backend.common.ResultUtils;
import com.ncu702.backend.model.dto.comment.CommentAddRequest;
import com.ncu702.backend.model.entity.Comment;
import com.ncu702.backend.model.entity.User;
import com.ncu702.backend.model.untils.TokeConfig;
import com.ncu702.backend.service.ArticleService;
import com.ncu702.backend.service.CommentService;
import com.ncu702.backend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.http.HttpRequest;
import java.util.ArrayList;
import java.util.Date;

@RestController
@RequestMapping("/api/comment")
@Slf4j
public class CommentController {

    @Resource
    private UserService userService;
    @Resource
    private CommentService commentService;
    @Resource
    private TokeConfig tokeConfig;


    //获取评论
    @GetMapping("/get")
    public BaseResponse<ArrayList<Comment>> getCommentByArticleId(@RequestParam(value = "articleId") String articleId){
        ArrayList<Comment> comments=commentService.getAllArticleByArticleId(articleId);
        return ResultUtils.success(comments);
    }


    //增加评论
    @PostMapping("/add")
    public BaseResponse<Boolean> doNewPost(
       @RequestBody CommentAddRequest req,
        HttpServletRequest request
    ){
        //获取jwt
        String jwtToken = request.getHeader("jwtToken");
        //鉴权
        boolean checkToke = tokeConfig.checkToke(jwtToken);
        if(!checkToke){
            return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR,"token失效");
        }
        User tokeMessage = tokeConfig.getTokeMessage(jwtToken);
        Long uid = tokeMessage.getUid();
        String role=userService.UserByUid(uid).getUserRole();
        if(role.equals("ban")){
            return ResultUtils.error(ErrorCode.FORBIDDEN_ERROR,"you are banned!");
        }



        Comment comment=new Comment();
        comment.setCid(UUID.randomUUID().toString());
        comment.setArticleId(req.getArticleId());
        comment.setUid(uid);
        comment.setContent(req.getContext());
        comment.setPostTime(new Date());
        Boolean b=commentService.addComment(comment);
        return ResultUtils.success(b);
    }


    //删除评论
    @GetMapping("/delete")
    public BaseResponse<Boolean> deleteCommentByCid(
            @RequestParam(value = "cid") String cid,
            HttpServletRequest request
    ){
        //获取jwt
        String jwtToken = request.getHeader("jwtToken");
        //鉴权
        boolean checkToke = tokeConfig.checkToke(jwtToken);
        if(!checkToke){
            return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR,"token失效");
        }
        Boolean b=commentService.deleteCommentByCid(cid);
        return ResultUtils.success(b);
    }
}
